#include "types.h"
#include "riscv.h"
#include "defs.h"
#include "date.h"
#include "param.h"
#include "memlayout.h"
#include "spinlock.h"
#include "proc.h"
#include "sysinfo.h"

uint64
sys_exit(void)
{
  int n;
  if (argint(0, &n) < 0)
    return -1;
  exit(n);
  return 0; // not reached
}

uint64
sys_getpid(void)
{
  return myproc()->pid;
}

uint64
sys_fork(void)
{
  return fork();
}

uint64
sys_wait(void)
{
  uint64 p;
  if (argaddr(0, &p) < 0)
    return -1;
  return wait(p);
}

uint64
sys_sbrk(void)
{
  int addr;
  int n;

  if (argint(0, &n) < 0)
    return -1;
  addr = myproc()->sz;
  if (growproc(n) < 0)
    return -1;
  return addr;
}

uint64
sys_sleep(void)
{
  int n;
  uint ticks0;

  if (argint(0, &n) < 0)
    return -1;
  acquire(&tickslock);
  ticks0 = ticks;
  while (ticks - ticks0 < n)
  {
    if (myproc()->killed)
    {
      release(&tickslock);
      return -1;
    }
    sleep(&ticks, &tickslock);
  }
  release(&tickslock);
  return 0;
}

uint64
sys_kill(void)
{
  int pid;

  if (argint(0, &pid) < 0)
    return -1;
  return kill(pid);
}

// return how many clock tick interrupts have occurred
// since start.
uint64
sys_uptime(void)
{
  uint xticks;

  acquire(&tickslock);
  xticks = ticks;
  release(&tickslock);
  return xticks;
}

uint64
sys_trace(void)
{
  int n;
  if (argint(0, &n) < 0)
    return -1;

  myproc()->trace_mask = n;
  return n;
}

uint64
sys_sysinfo(void)
{
  struct sysinfo info;
  uint64 addr;
  if (argaddr(0, &addr) < 0)
  {
    return -1;
  }
  info.num_freemem = get_free_mem();
  info.num_unusedproc = get_proc_unused();
  if (copyout(myproc()->pagetable, addr, (char *)&info, sizeof(info)) < 0)
  {
    return -1;
  }
  return 0;
}

uint64
sys_pgaccess(void)
{
  uint64 va;
  int nsize;
  uint64 user_buff;

  argaddr(0, &va);
  argint(1, &nsize);
  argaddr(2, &user_buff);
  // pgaccess(&va, nsize, &user_buff);

  pte_t *pte;
  uint64 ker_buff;
  if (va > MAXVA)
  {
    panic("pgaccess:va > MAXVA");
  }
  if (nsize > 32)
  {
    panic("pgaccess:nsize > 32");
  }

  pagetable_t pgtable = myproc()->pagetable;
  for (int i = 0; i < nsize; i++)
  {
    pte = walk(pgtable, va + PGSIZE * i, 0);
    if ((*pte & (PTE_V | PTE_A)))
    {
      ker_buff |= 1 << i;
      *pte ^= PTE_A;
    }
  }
  copyout(pgtable, user_buff, (char *)&ker_buff, sizeof(ker_buff));
  return 0;
}
